package com.wasp.collector.service;

import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;

import com.google.common.collect.Maps;
import com.wasp.collector.content.IContentHandler;
import com.wasp.collector.data.RequestWrapper;

public class CollectorHelper {

	private static final Object objLock = new Object();

	private static Map<String, IContentHandler> handlers = Maps.newConcurrentMap();
	private static Map<String, Date> handlerRegisterDate = Maps.newConcurrentMap();

	static {
		autoDestroy();
	}

	private static void autoDestroy() {
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				for(Entry<String, Date> entry : handlerRegisterDate.entrySet()){
					Date now = new Date();
					if(now.getTime() - entry.getValue().getTime()>(24*3600*1000)){
						destroy(entry.getKey());
					}
				}
			}
		}, 10*60*1000, 60*60*1000);
	}
	private static void destroy(String id){
		if(handlers.containsKey(id)){
			handlers.remove(id);
			handlerRegisterDate.remove(id);
		}
	}
	public static void resgister(RequestWrapper wrapper,IContentHandler handler){
		synchronized (objLock) {
			handlers.put(wrapper.getId(),handler);
			handlerRegisterDate.put(wrapper.getId(), new Date());
		}
	}
	public static void destroy(RequestWrapper wrapper){
		String id = wrapper.getId();
		destroy(id);
	}
	public static IContentHandler getHandler(RequestWrapper wrapper){
		if(handlers.containsKey(wrapper.getId())){
			return handlers.get(wrapper.getId());
		}
		throw new RuntimeException("no handler for wrapper :"+ wrapper.getId());
	}
}